package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-21 19:07
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlipayServiceImpl implements AlipayService {

	private final AlipayClient alipayClient;

	private final PaymentService paymentService;

	private final OrderFeignClient orderFeignClient;

	/**
	 * @see <a href="https://opendocs.alipay.com/open/270/105899"/>
	 */
	@SneakyThrows
	@Override
	public String createAliPay(Long orderId) {
		OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
		// 生成二维码的同时 保存交易记录
		paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
		// 如果订单已经关闭 则不生成二维码
		if ("CLOSED".equals(orderInfo.getOrderStatus())) {
			return "该订单已经取消!";
		}

		// 创建API对应的request
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		// 同步回调
		// https://www.domain.com/CallBack/return_url?out_trade_no=930a1f5a-e217-40af-a022-4c1ce1fd866e1645444520751
		// &version=1.0&app_id=2021001163617452&charset=utf-8&sign_type=RSA2&trade_no=2022022122001481701452463560
		// &auth_app_id=2021001163617452&timestamp=2022-02-21%2019:56:19&seller_id=2088831489324244
		// &method=alipay.trade.page.pay.return&total_amount=0.01
		// &sign=MYvCDt29R3u4+4mBvPPk7Ulw1lfmdWLzGKqp0B4Mo/85soJy+1AB00lvsqbDT3PJ3cPMUFCW6famcb1PSFCuKh1dp27SUgID4T5HEA+R14SzUuNdY6igw+9G/7YiUfohl+gy6H8bvEc8509mL4HTFBt3E0hfC+I7fVz+pWmphFdqCxokEJTTRJVFI48dNBzGetgT0rBauDAgC4oEynT3RLdvn/gawlp95meZkaun79FCrg7Ubo81G64X/EBYuUtPSUZrdhJOpCMoIzzefCVxGyh5oWZA53RhuoeZ7YPIeSKMz7flGxTrkA0RAlWVeP6k/nBMcULY+/CixXuqQFtteQ==
		alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
		// 异步回调
		alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
		// 填充业务参数
		HashMap<String, Object> map = new HashMap<>();
		map.put("out_trade_no", orderInfo.getOutTradeNo());
		map.put("product_code", "FAST_INSTANT_TRADE_PAY");
		map.put("total_amount", "0.01");
		map.put("subject", StringUtils.isBlank(orderInfo.getTradeBody()) ? "无" : orderInfo.getTradeBody());

		log.info("业务参数:{}", JSON.toJSONString(map));

		alipayRequest.setBizContent(JSON.toJSONString(map));

		return alipayClient.pageExecute(alipayRequest).getBody();
	}

	/**
	 * 申请退款
	 */
	@SneakyThrows
	@Override
	public boolean refund(Long orderId) {
		OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		Map<String, Object> map = new HashMap<>();
		map.put("out_trade_no", orderInfo.getOutTradeNo());
		map.put("refund_amount", "0.01");
		map.put("refund_reason", "退款原因");
		request.setBizContent(JSON.toJSONString(map));
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			log.info("退款成功");
			// 关闭订单
			PaymentInfo paymentInfo = new PaymentInfo();
			paymentInfo.setPaymentStatus(PaymentStatus.ClOSED.name());
			paymentService.updatePaymentInfo(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name(), paymentInfo);
		}
		else {
			log.info("退款失败");
		}
		return response.isSuccess();
	}

	/**
	 * 关闭支付宝交易
	 */
	@SneakyThrows
	@Override
	public Boolean closePay(Long orderId) {
		OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);

		AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
		request.setBizContent(bizContent.toString());
		AlipayTradeCloseResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			System.out.println("调用成功");
		}
		else {
			System.out.println("调用失败");
		}
		return response.isSuccess();
	}

	/**
	 * 查询是否存在交易记录
	 */
	@SneakyThrows
	@Override
	public Boolean checkPayment(Long orderId) {
		OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);

		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("out_trade_no", orderInfo.getOutTradeNo());

		request.setBizContent(bizContent.toString());
		AlipayTradeQueryResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			System.out.println("调用成功");
		}
		else {
			System.out.println("调用失败");
		}
		return response.isSuccess();
	}

}
